package com.supermap.wzhy.module.user.service;

import com.supermap.wzhy.entity.TRolepowerrelation;
import com.supermap.wzhy.entity.TUserpower;
import com.supermap.wzhy.entity.TUserrole;
import com.supermap.wzhy.module.user.dao.RolepowerrelationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * Created by Linhao on 2014/9/19.
 */
@Service
public class RolePowerRelationService {

    @Autowired
    RolepowerrelationDao rolepowerrelationDao;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    PowerService powerService;

    public boolean create(TRolepowerrelation tRolepowerrelation) {
        if(tRolepowerrelation != null){
            rolepowerrelationDao.save(tRolepowerrelation);
            return true;
        }
        return false;
    }

    public boolean delete(int id) {
        TRolepowerrelation tRolepowerrelation = rolepowerrelationDao.findOne(id);
        if(tRolepowerrelation != null){
            rolepowerrelationDao.delete(tRolepowerrelation);
            return  true;
        }
        return  false;
    }

    public boolean update(int id,TRolepowerrelation tRolepowerrelationEntity) {
        TRolepowerrelation tRolepowerrelation = rolepowerrelationDao.findOne(id);
        if(tRolepowerrelation!=null){
            rolepowerrelationDao.save(tRolepowerrelationEntity);
            return  true;
        }
        return false;
    }

    /**
     * 设置角色权限(先删除已有的所有权限，再重新设置)
     *
     * @param roleId
     *          roleId
     * @param powerids
     *          多个powerid
     * @return
     */
    public int setRolepower(int roleId,int[] powerids) {
       int re = -1;
       TUserrole tUserrole = userRoleService.one(roleId);
       if(tUserrole != null){
           String sql = "delete from T_ROLEPOWERRELATION t where t.roleid=?";
           rolepowerrelationDao.executeBySql(sql,tUserrole.getRoleid());

           if(powerids != null ){
               re = 0;
               for (int powerid : powerids){
                   TUserpower tUserpower = powerService.getOne(powerid);
                   if(tUserpower != null){
                       TRolepowerrelation tRolepowerrelation = new TRolepowerrelation();
                       tRolepowerrelation.setTUserpower(tUserpower);
                       tRolepowerrelation.setTUserrole(tUserrole);

                       rolepowerrelationDao.save(tRolepowerrelation);

                       re++;
                   }
               }
           }
       }

       return re;
    }
}
